'use strict';

const keyContrulor = require('./../lib/keyContrulor');

const Controller = require('egg').Controller;

class UserController extends Controller {
  async index() {
    const { ctx } = this;
    // ctx.body = 'hi, user';
    ctx.body = await ctx.model.User.find();
  }

  async registerAdmin() {
    const { ctx } = this;
    const { body = {} } = ctx.request;
    const { name, password, phone, email, sex = 0, age = 0, lv } = body;
    if (!name || !password || !phone || !email || ![ 0, 1, 2 ].includes(lv)) {
      ctx.body = {
        success: false,
        msg: 'name, password, phone, email,lv都是必传字段！',
        data: null,
      };
      return;
    }
    // 校验手机号唯一
    const findOneByPhone = await ctx.model.User.findOne({
      phone,
    });
    if (!findOneByPhone) {
      // 通过校验
      // 解密字段
      const real_pw = await keyContrulor.decrypt(password);
      // 用户数据入库
      await ctx.model.User.create({
        name,
        phone,
        email,
        sex,
        age,
        lv,
        password: real_pw,
      });
      ctx.body = {
        success: true,
        msg: '注册成功',
        data: null,
      };
      return;

    }
    // 已存在手机号相同的用户数据
    ctx.body = {
      success: false,
      msg: '已存在手机号相同的用户数据！',
      data: null,
    };
    return;

  }
  async getUserList() {
    const { ctx } = this;
    console.log('body:', ctx.request.body);
    // ctx.body = 'hi, user';
    ctx.body = await ctx.model.User.find();
  }
  async createUser() {
    const { ctx } = this;
    // ctx.body = 'hi, user';
    ctx.body = await ctx.model.User.find();
  }
}

module.exports = UserController;
